package org.xnat.xnatfs.connection;

import static org.junit.Assert.*;
import static org.mockito.Mockito.*;

import javax.servlet.http.HttpServletRequest;

import org.junit.Before;
import org.junit.Test;

public class TestXnatContextProvider {
  private IsolatedXnatContextProvider provider;
  private HttpServletRequest request;

  @Before
  public void setUp () throws Exception {
    provider = new IsolatedXnatContextProvider ();

    request = mock ( HttpServletRequest.class );
    provider.setRequest ( request );
  }

  @Test
  public void shouldHandleNonRootWebapp () {
    setPathInfo ( "/" );
    setContextPath ( "/xnat" );
    setServletPath ( "/fs" );
    setRequestURI ( "/xnat/fs/" );
    setRequestURL ( "http://localhost:8080/xnat/fs/" );

    assertEquals ( "http://localhost:8080/xnat/REST", provider.getRestURL () );
  }

  @Test
  public void shouldHandleRootWebapp () {
    setPathInfo ( "/" );
    setContextPath ( "" );
    setServletPath ( "/fs" );
    setRequestURI ( "/fs/" );
    setRequestURL ( "http://localhost:8080/fs/" );

    assertEquals ( "http://localhost:8080/REST", provider.getRestURL () );
  }

  private void setRequestURL ( String value ) {
    StringBuffer sb = new StringBuffer ();
    sb.append ( value );
    when ( request.getRequestURL () ).thenReturn ( sb );
  }

  private void setContextPath ( String value ) {
    when ( request.getContextPath () ).thenReturn ( value );
  }

  private void setPathInfo ( String value ) {
    when ( request.getPathInfo () ).thenReturn ( value );
  }

  private void setServletPath ( String value ) {
    when ( request.getServletPath () ).thenReturn ( value );
  }

  private void setRequestURI ( String value ) {
    when ( request.getRequestURI () ).thenReturn ( value );
  }

  private static class IsolatedXnatContextProvider extends XnatContextProvider {
    private HttpServletRequest request;

    @Override
    protected HttpServletRequest getRequest () {
      return request;
    }

    public void setRequest ( HttpServletRequest request ) {
      this.request = request;
    }

  }
}
